// AdBlockerBHO.cpp : Implementation of CAdBlockerBHO

#include "stdafx.h"
#include "Shlobj.h"
#include <boost/algorithm/string.hpp>

#include "AdBlockerBHO.h"
#include "RegistryManager.h"
#include <iostream>
#include <fstream>
#include <exception>
#include "Exceptions.h"
#include "FilterList.h"

STDMETHODIMP CAdBlockerBHO::SetSite(IUnknown* pUnkSite)
{
	try
	{
		if (pUnkSite != NULL)
		{
			HRESULT hr = S_OK;
			// Cache the pointer to IWebBrowser2.
			hr = pUnkSite->QueryInterface(IID_IWebBrowser2, (void **)&_webBrowser);
			if (SUCCEEDED(hr))
			{				
				// Register to sink events from DWebBrowserEvents2.
				hr = DWebBrowserEvents2Sink::DispEventAdvise(_webBrowser);
				if (SUCCEEDED(hr))
				{
					//CFilterList filterList;
					//filterList.InitializeFromAdblockPlusFiltersFile("adblock-pxf-polish.txt");
					////serializing
					//{
					//ofstream fileStream("adblock-pxf-polish[serialized].txt");
					//boost::archive::text_oarchive outputArchive(fileStream);
					//outputArchive << filterList;
					//}					

					_advertBlocker.LoadResources();
				}			
			}
		}
		else
		{
			// Unregister event sink.
			if (_isWebBrowserAdvised)
			{
				DWebBrowserEvents2Sink::DispEventUnadvise(_webBrowser);
				_isWebBrowserAdvised = false;
			}

			// Release cached pointers and other resources here.
			_webBrowser.Release();

			
		}

		// Call base class implementation.
		return IObjectWithSiteImpl<CAdBlockerBHO>::SetSite(pUnkSite);
	}
	catch(RegistryException& e)
	{
		MessageBox(NULL, L"Error with registry setting", L"IE AdBlocker", MB_OK | MB_ICONERROR);
	}
	catch(exception e)
	{
		MessageBox(NULL, L"Error", L"IE AdBlocker", MB_OK | MB_ICONERROR);
	}
}

void STDMETHODCALLTYPE CAdBlockerBHO::OnDocumentComplete(IDispatch *pDisp, VARIANT *pvarURL)
{
	try
	{
		bool blockingOn = _regMgr.IsAdblockerTurnedOn();

		HRESULT hr = S_OK;

		// Query for the IWebBrowser2 interface.
		CComQIPtr<IWebBrowser2> tempWebBrowser = pDisp;

		// Is this event associated with the top-level browser?
		if (tempWebBrowser && _webBrowser &&
			_webBrowser.IsEqualObject(tempWebBrowser)
			&& blockingOn)
		{
		
			_advertBlocker.Initialize(_webBrowser);
			_advertBlocker.RemoveAdverts(_webBrowser);	
		}
	}
	catch(RegistryException& e)
	{
		MessageBox(NULL, L"Error with registry setting", L"IE AdBlocker", MB_OK | MB_ICONERROR);
	}
	catch(exception e)
	{
		MessageBox(NULL, L"Error", L"IE AdBlocker", MB_OK | MB_ICONERROR);
	}
}

void STDMETHODCALLTYPE CAdBlockerBHO::OnBeforeNavigate2(IDispatch *pDisp, VARIANT *url, VARIANT *Flags, VARIANT *TargetFrameName, VARIANT *PostData, VARIANT *Headers, VARIANT_BOOL *Cancel)
{
	_advertBlocker.CleanUpAfterInitialization();
}

// CAdBlockerBHO

